import { PageConfig } from 'next';
import anylogger from 'anylogger';
import '@mmstudio/an000042';
import an48 from '@mmstudio/an000048';
import { tbfdrolemenu } from '../../../../../atoms/db';

const logger = anylogger('pages/api/admin/role/menus/save.api');

export type Result = {
	ok: true;
} | {
	ok: false;
	message: string;
};

export type Message = {
	roleid: string;
	menuids: string[];
}

/**
 * 保存当前角色分配的菜单
 */
const handler = an48<Result>();

handler.put(async (req, res) => {
	try {
		logger.debug('msg body:', req.body);
		const { menuids = [], roleid } = req.body as Message;
		if (!roleid) {
			res.status(200).json({
				ok: false,
				message: '角色id为空'
			});
			return;
		}
		// remove first
		await tbfdrolemenu()
			.del()
			.where({
				roleid
			});

		// insert new records now
		if (menuids.length > 0) {
			await tbfdrolemenu()
				.insert(menuids.map((it) => {
					return {
						menuid: it,
						roleid
					};
				}));
		}

		res.status(200).json({ ok: true });
	} catch (error) {
		logger.trace(error);
		res.status(200).json({ ok: false, message: (error as Error).message });
	}
});

export const config = {} as PageConfig;

export default handler;
